﻿using BrnMall.Manager.Domain.AddressBook;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BrnMall.Manager.Manager.AddressBook
{
    /// <summary>
    /// 客户跟进管理
    /// </summary>
    public class ClientFollowManager
    {
        /// <summary>
        /// 添加客户跟进语
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool Add(ClientFollow model)
        {
            using (var db = new QDMallDatabase())
            {
                db.Insert(model);
            }
            return model.Id > 0;
        }

        public static Page<ClientFollow> GetClientFollowListPages(int staffid, int clientid, int page, int pageSize = 10)
        {
            var sql = new StringBuilder();
            sql.AppendFormat("select * from crm_ClientFollow where Staffid={0} and ClientId={1}", staffid, clientid);
            sql.Append(" order by addtime desc");
            using (var db = new QDMallDatabase())
            {
                return db.Page<ClientFollow>(page, pageSize, sql.ToString());
            }
        }
        public static ClientFollow GetClientFollowByid(int id)
        {
            using (var db = new QDMallDatabase())
            {
                string sql = string.Format("select top 1 * from crm_ClientFollow where clientid={0} order by addtime desc", id);
                return db.SingleOrDefault<ClientFollow>(sql, id);
            }
        }

        public static FollowDateView GetFollowDays(int staffId, int clientId)
        {
            var sql = $"select max(addTime) as lastAddtime,MIN(addTime) as firstAddTime from crm_ClientFollow where StaffId={staffId} and clientId={clientId}";
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<FollowDateView>(sql.ToString());
            }
        }

        /// <summary>
        /// 跟进总数
        /// </summary>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public static int GetFollowTotal(int staffId)
        {
            using (var db = new QDMallDatabase())
            {
                return db.ExecuteScalar<int>($"select COUNT(1) as counts from crm_ClientFollow where StaffId={staffId}");
            }
        }



        public static int Update(int StaffId,int NewStaffId) {
            using (var db = new QDMallDatabase())
            {
                return db.Execute(string.Format("update crm_ClientFollow set StaffId={0} where StaffId={1}", NewStaffId, StaffId));
            }
        }
    }
}
